/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

/**
 *
 * @author xiaoliang
 */
public class HttpPostHelper {

    private static Logger logger = Logger.getLogger(HttpPostHelper.class.getName());
    private String ip;
    private CloseableHttpClient client;

    public HttpPostHelper(String ip) {
        this.ip = ip;
        initClient();
    }

    public void initClient() {
        if (client == null) {
            client = HttpClients.createDefault();
        }
    }

    public String postMsg(Map<String, String> postMsg) throws IOException {
        Thread.currentThread().setName("httpPost" + System.nanoTime());
        HttpPost post = new HttpPost(ip);
        List<NameValuePair> params = new ArrayList<>();
        Set<String> keys = postMsg.keySet();
        for (String key : keys) {
            params.add(new BasicNameValuePair(key, postMsg.get(key).toString()));
        }
        post.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse response = client.execute(post);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();//是否发送成功，200即为成功
        InputStream is = response.getEntity().getContent();//得到返回流，读取并操作。
        String result = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        return result;
    }
    
    public CloseableHttpClient getClient(){
        return client;
    }
}
